import Cookies from "js-cookie";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { adminInfoAPI } from "../request/api";
import store from "../store";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login.vue"),
  },
  //homepage页面其实可以不写，因为一直没有进入该路由
  // {
  //   path: "/homePage",
  //   name: "homePage",
  //   component: () => import("../views/HomePage.vue"),
  // },
  // {
  //   path: "/pms",
  //   name: "pms",
  //   component: () => import("../views/HomePage.vue"),
  //   children: [
  //     {
  //       path: "product",
  //       name: "product",
  //       component: () => import("../views/pms/product.vue"),
  //     },
  //     {
  //       path: "addProduct",
  //       name: "addProduct",
  //       component: () => import("../views/pms/addProduct.vue"),
  //     }
  //   ],
  // },
];

const router = createRouter({
  history: createWebHashHistory(), //hash模式
  routes,
});

//抽离动态添加路由
const genRouter = () => {
  //添加动态路由===========
  //获取vuex存储的路由信息
  let menus = store.getters.getNewMenus;
  // 遍历获取菜单信息
  for (let key in menus) {
    //一级菜单
    let routerObj: RouteRecordRaw = {
      path: "/" + menus[key].name,
      name: menus[key].name,
      component: () => import("../views/HomePage.vue"),
      children: [],
    };
    menus[key].children.forEach((item: MenusItem) => {
      //二级菜单
      routerObj.children!.push({
        path: item.name,
        name: item.name,
        //路由元信息存面包屑数据
        meta: {
          name: menus[key].title,
          path: "/" + menus[key].name + "/" + menus[key].children[0].name,
          childName: item.title,
        },
        component: () => import(`../views/${menus[key].name}/${item.name}.vue`),
      });
    });
    //添加路由
    router.addRoute(routerObj);
  }
};
//前置路由守卫
router.beforeEach(async (to, from, next) => {
  //注册首页路由，所有用户都可以访问，但是需要登录才能访问
  router.addRoute({
    path: "/",
    name: "homepage",
    redirect: "/index",

    component: () => import("../views/HomePage.vue"),
    children: [
      {
        path: "/index",
        name: "index",
        component: () => import("../views/Index.vue"),
        meta: {
          name: "首页",
          path: "/index",
          childName: "首页",
        },
      },
    ],
  });

  //刷新的时候from是/  to是当前页面 因为刷新后路由历史清空
  //刷新判断用户是否已经登录并且vuex用户信息为空（页面刷新会清空vuex数据），为空则从新获取用户信息
  let token = Cookies.get("token");
  if (token && store.state.menus.length === 0) {
    //获取当前登录用户信息
    await store.dispatch("getAdminInfo");
    genRouter();
    // //获取当前登录用户信息
    // let resUserInfo = await adminInfo();
    // if (resUserInfo.code === 200) {
    //   store.commit("updateMenus", resUserInfo.data.menus);
    // }
    // genRouter();
    console.log("刷新");
    //避免刷新后找找不到路由(router官网有说addrouter添加路由并不会触发新的导航。也就是说，除非触发新的导航，否则不会显示所添加的路由。)
    next(to);
  } else if (
    token &&
    store.state.menus.length > 0 &&
    to.path == "/homePage" &&
    from.path == "/login"
  ) {
    genRouter();
    console.log("首次登陆");

    //使用to会造成死循环，该if条件一直成立
    next("/index");
  } else if (!token && to.path !== "/login") {
    //没登录并且不是去登录页面时跳转让用户从新登录
    next("/login");
  } else if (token && to.path === "/login") {
    //已经登陆，只让点击退出登录或者删除token后才可以回到登录页面
    next(from);
  } else {
    next();
  }
});

export default router;
